<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Common\ApiHelper;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;


class LoginController extends Controller
{
    //加载登录页面
    public function index()
    {
        return view('login.index');
    }


    public function loginOperation(Request $request)
    {
        $username = $request->get('username');
        $user = User::query()->where('username', $username)->first();
        if (!$user) {
            //创建用户
            DB::beginTransaction();
            try {
                $user = User::query()->create([
                    'username' => $username
                ]);
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                Log::info('创建用户-失败', ['data' => $exception->getMessage()]);
                return ApiHelper::responseError('注册失败,请稍后再试');
            }
        }
        $token = auth('api')->login($user);
        $data = [
            'access_token' => 'Bearer ' . $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60,
        ];
        session(['user' => $data]);
        return redirect()->route('im.indexList');
    }

}
